const RBAC = require('./rbac-a');
const Provider = RBAC.providers.JsonProvider;

module.exports = function (options, app) {
	
	const getRules = async function () {};
	const getUser = async function () {};
	return async (ctx, next) => {
		const module = ctx.module;
		const controller = ctx.controller;
		const action = ctx.action.toUpperCase();
		// 只支持以下方法
		if(['GET', 'POST', 'DELETE', 'PUT', 'PATCH'].indexOf(action) === -1) {
			return ctx.fail(1000, `资源没有授权访问`, '');
		}
		const path = `/${module}/${controller}`;
		
		// 不验证的路由
		if(path.match(/^\/admin\/token/)) {
			// 注册登录
			return next();
		}
		
		const rbac = new RBAC({
			provider: new Provider(getRules()) //需要动态获取规则，后台修改授权必须重启服务才能使规则生效
		});
		const auth = await rbac.checkPath(getUser(), path, action);
		
		if(!auth) {
			return ctx.fail(1000, `没有授权访问”${path}“`);
		}
		
		return next();
	};
};
